import { baseUrl } from '@/config/baseUrl.js';

/**
 * 图片上传工具函数
 * @param {Object} options 配置选项
 * @param {number} [options.count=1] - 选择图片数量
 * @param {Array} [options.sizeType=['original', 'compressed']] - 图片类型
 * @param {Array} [options.sourceType=['album']] - 图片来源
 * @param {string} [options.url=baseUrl + '/wx/upload/image'] - 上传接口地址
 * @param {string} [options.name='file'] - 文件字段名
 * @param {Object} [options.formData={}] - 额外表单数据
 * @param {number|boolean} [options.maxSize] - 最大文件大小(MB)，设为true时使用默认5MB
 * @param {boolean} [options.showProgress=false] - 是否显示上传进度
 * @returns {Promise} 返回Promise对象
 */
export const uploadImage = (options = {}) => {
	return new Promise((resolve, reject) => {
		// 合并默认配置
		const config = {
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			url: baseUrl + '/wx/upload/image',
			name: 'file',
			formData: {},
			showProgress: false,
			...options
		};
		// 处理maxSize参数
		const maxSizeInBytes = config.maxSize === true ? 5 * 1024 * 1024 : typeof config.maxSize === 'number' ? config.maxSize * 1024 * 1024 : null;

		// 选择图片
		uni.chooseImage({
			count: config.count,
			sizeType: config.sizeType,
			sourceType: config.sourceType,
			success: async (chooseRes) => {
				try {
					const tempFilePaths = chooseRes.tempFilePaths;
					// 检查文件大小
					if (maxSizeInBytes) {
						const sizeCheckResults = await Promise.all(
							tempFilePaths.map((path) => {
								return new Promise((resolve) => {
									uni.getFileInfo({
										filePath: path,
										success: (info) => {
											resolve(info.size <= maxSizeInBytes);
										},
										fail: () => resolve(false)
									});
								});
							})
						);

						if (!sizeCheckResults.every((r) => r)) {
							uni.showToast({
								title: `图片不能超过${config.maxSize === true ? 5 : config.maxSize}MB`,
								icon: 'none'
							});
							reject(new Error('图片大小超过限制'));
							return;
						}
					}

					// 显示加载中
					if (config.showProgress) {
						uni.showLoading({
							title: '准备上传...',
							mask: true
						});
					}

					// 上传图片
					const uploadTasks = tempFilePaths.map((filePath) => {
						return new Promise((uploadResolve, uploadReject) => {
							const task = uni.uploadFile({
								url: config.url,
								filePath: filePath,
								name: config.name,
								formData: config.formData,
								success: (uploadRes) => {
									try {
										// 尝试解析返回数据
										const data = typeof uploadRes.data === 'string' ? JSON.parse(uploadRes.data) : uploadRes.data;
										uploadResolve(data);
									} catch (e) {
										console.error('解析上传结果失败:', e);
										uploadResolve(uploadRes.data); // 返回原始数据
									}
								},
								fail: (err) => {
									uploadReject(err);
								}
							});

							// 监听上传进度
							if (config.showProgress) {
								task.onProgressUpdate((progress) => {
									uni.showLoading({
										title: `上传中 ${progress.progress}%`,
										mask: true
									});

									if (progress.progress === 100) {
										uni.showLoading({
											title: '处理中...',
											mask: true
										});
									}
								});
							}
						});
					});

					// 等待所有上传任务完成
					const results = await Promise.all(uploadTasks);

					if (config.showProgress) {
						uni.hideLoading();
					}

					resolve(config.count === 1 ? results[0] : results);
				} catch (error) {
					if (config.showProgress) {
						uni.hideLoading();
					}
					reject(error);
				}
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};

export const formatTime = (date) => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();

	return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`;
};
/**
 * 时差计算
 * 返回时间戳
 */
export const fixTimezoneOffset = (time) => {
	const date = new Date(time);
	// 当前时间 = 包含时差的当前时间 - 时差时间，getTimezoneOffset() 获取时差（以分钟为单位），转为小时需要除以 60
	// date.setHours(date.getHours() - date.getTimezoneOffset() / 60)
	return date.getTime();
};
export const formatNumber = (n) => {
	n = n.toString();
	return n[1] ? n : `0${n}`;
};
const formatDateToMMDD = (timestamp) => {
	const date = new Date(timestamp);
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	return `${month}-${day}`;
};
// 格式化函数，返回 yyyy-MM-dd 格式
const formatDateToYYYYMMDD = (timestamp) => {
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	return `${year}-${month}-${day}`;
};
/**
 * 时间计算
 * 参数为时间戳
 */
export const timeago = (date) => {
	let dateTimeStamp = fixTimezoneOffset(date);
	var minute = 1000 * 60;
	var hour = minute * 60;
	var day = hour * 24;
	var now = new Date().getTime(); // 获取当前时间毫秒
	var diffValue = now - dateTimeStamp; // 时间差

	if (diffValue < 0) {
		return '刚刚';
	}

	var year = new Date(dateTimeStamp).getFullYear();
	var currentYear = new Date().getFullYear();

	// 如果超过一年或不是当年，返回完整日期 yyyy-MM-dd
	if (year !== currentYear || diffValue >= day * 365) {
		return formatDateToYYYYMMDD(dateTimeStamp);
	}

	// 计算时间差的分，时，天
	var dayC = diffValue / day;
	var hourC = diffValue / hour;
	var minC = diffValue / minute;

	if (dayC >= 4) {
		// 超过4天返回 MM-dd
		return formatDateToMMDD(dateTimeStamp);
	} else if (dayC >= 1) {
		// 超过1天返回 n天前
		return parseInt(dayC) + '天前';
	} else if (hourC >= 1) {
		// 超过1小时返回 n小时前
		return parseInt(hourC) + '小时前';
	} else if (minC >= 1) {
		// 超过1分钟返回 n分钟前
		return parseInt(minC) + '分钟前';
	} else {
		// 不足1分钟返回 刚刚
		return '刚刚';
	}
};

// 处理title首行缩进
export const getTHDValue = (item) => {
	if (item.isTop == 1 && item.isDigest == 1) {
		return item.isHot == 1 ? 3 : 2;
	}
	if (item.isHot == 1 && item.isTop == 0 && item.isDigest == 0) {
		return 4;
	}
	if (item.isHot == 1) {
		return 0;
	}
	if (item.isTop == 1 || item.isDigest == 1) {
		return 1;
	}
	return 5;
};

/**
 * 处理帖子数组
 */
export const dealWithData = (list) => {
	const newList = list.map((item) => {
		item = dealWithDataItem(item, 0);
		return item;
	});
	return newList;
};

/**
 * 处理单个帖子
 */
export const dealWithDataItem = (item, isItem) => {
	const isTHD = getTHDValue(item);
	if (isItem == 1) {
		if (item.imageUrls.length > 4) {
			item.imageUrls.slice(0, 4);
		}
	}
	item.createTime = timeago(item.createTime);
	const LVNum = 'LV.' + item.author.usergroup.level + item.author.usergroup.groupTitle;
	item.LVNum = LVNum;
	item.isTHD = isTHD;
	item.avatar = item.author.avatar;
	item.nickname = item.author.nickname;
	return item;
};
/**
 * 处理单个跑腿
 */
export const errandsItem = (item) => {
	let helpTypeContent = '';
	let class1 = '';
	switch (item.helpType) {
		case 1:
			helpTypeContent = '跑腿';
			class1 = 'tab1';
			break;
		case 2:
			helpTypeContent = '帮我送';
			class1 = 'tab3';
			break;
		case 3:
			helpTypeContent = '帮我买';
			class1 = 'tab2';
			break;
		case 4:
			helpTypeContent = '帮我取';
			class1 = 'tab4';
			break;
		default:
			helpTypeContent = '';
			class1 = '';
	}
	let orderStatusContent = '';
	let class2 = '';
	switch (item.orderStatus) {
		case -6:
			orderStatusContent = '冻结订单已处理';
			class2 = 'state4';
			break;
		case -5:
			orderStatusContent = '冻结订单已处理';
			class2 = 'state4';
			break;
		case -4:
			orderStatusContent = '订单冻结中';
			class2 = 'state4';
			break;
		case -3:
			orderStatusContent = '订单被管理员退回';
			class2 = 'state1';
			break;
		case -2:
			orderStatusContent = '发单人已取消';
			class2 = 'state3';
			break;
		case -1:
			orderStatusContent = '接单人已取消';
			class2 = 'state3';
			break;
		case 0:
			orderStatusContent = '待帮助';
			class2 = 'state0';
			break;
		case 1:
			orderStatusContent = '进行中';
			class2 = 'state0';
			break;
		case 2:
			orderStatusContent = '骑手已完成，待确认';
			class2 = 'state2';
			break;
		case 3:
			orderStatusContent = '已完成';
			class2 = 'state2';
			break;
		default:
			class2 = '';
			orderStatusContent = '';
	}
	item.helpTypeContent = helpTypeContent;
	item.class1 = class1;
	item.orderStatusContent = orderStatusContent;
	item.class2 = class2;
	return item;
};
